package com.denso.store.admin.template;

import com.denso.store.common.model.Scheduler;
import com.denso.store.common.model.Template;
import com.xiaoleilu.hutool.date.DateUtil;

import java.util.Date;
import java.util.List;

/**
 * Created by lijian on 2017/10/24.
 */
public class TemplateService {

    private static final Template dao = new Template();

    public List<Template> findByGroupId(int groupId) {
        return dao.find("select * from template where groupId=?", groupId);
    }

    public Template findById(int id) {
        return dao.findById(id);
    }

    public boolean save(Template template) {
        return template.save();
    }

    public boolean update(Template template) {
        template.setUpdateTime(new Date());
        return template.update();
    }

    public boolean deleteById(int id) {
        return dao.deleteById(id);
    }

    public int activeTemplate(int gid, String dateStr) {
        List<Template> templateList = findByGroupId(gid);
        for(Template template : templateList) {
            Scheduler scheduler = createScheduler(dateStr, template);
            scheduler.save();
        }
        return templateList.size();
    }

    private Scheduler createScheduler(String dateStr, Template template) {
        Scheduler scheduler = new Scheduler();
        scheduler.setCompany(template.getCompany());
        scheduler.setVan(template.getVan());
        scheduler.setPosition(template.getPosition());
        int hour = template.getHour();
        int minute = template.getMinute();
        String timeStr = dateStr + " " + hour + ":" + minute;
        Date planTime = DateUtil.parse(timeStr, "yyyy-MM-dd HH:mm");
        scheduler.setPlanTime(planTime);

        return  scheduler;
    }
}
